package com.itheima.reggin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggin.common.R;
import com.itheima.reggin.dto.DishDto;
import com.itheima.reggin.entity.Category;
import com.itheima.reggin.entity.Dish;
import com.itheima.reggin.entity.DishFlavor;
import com.itheima.reggin.service.CategoryService;
import com.itheima.reggin.service.DishFlavorService;
import com.itheima.reggin.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 * @author YCH
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;



    /*
     * 增
     * @param dishDto
     * @return
     */
    @CacheEvict(value = "dishCache",key="'dish_'+#dishDto.getCategoryId()+'_'+#dishDto.getStatus()" )
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 查
     * @param page
     * @param pageSize
     * @param name]
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> query = new LambdaQueryWrapper<>();
        query.like(name != null, Dish::getName, name);
        query.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, query);
        ///菜品信息已经查出来了，但是菜品分类没有查出来，表中只有分类的id
        Page<DishDto> dishDtoPage = new Page<>();
        //pageInfo里面的records是一个list集合里面记录的就是查询到的数据，我们需要先对他进行处理，然后才能展示
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 查询菜品信息和口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 改
     * @param dishDto
     * @return
     * 某一个菜品修改，那么这个这个菜品对应的分类的缓存就要删除
     */
    @CacheEvict(value = "dishCache",key="'dish_'+#dishDto.getCategoryId()+'_'+#dishDto.getStatus()" )
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        return R.success("保存菜品成功");
    }

    /**
     * 删除
     * 单个删除和批量删除，其实口味表没有删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String>  delete(@RequestParam List<Long> ids){
        for (int i = 0; i < ids.size(); i++) {
            dishService.removeById(ids.get(i));
        }
        return R.success("操作成功！");
    }

    /**
     * 停售/起售----批量
     */
    @PostMapping("/status/{ss}")
    public R<String> updataStatus(@PathVariable Integer ss,@RequestParam  List<Long> ids){
        for (int i = 0; i < ids.size(); i++) {
            Dish dish = dishService.getById(ids.get(i));
            dish.setStatus(ss);
            dishService.updateById(dish);
        }
        return R.success("操作成功！");

    }


    /**
     * 2，新增套餐时，查询每个菜品分类对应的dish
     * 3，移动用户首页端：展示每个分类（菜品分类，套餐分类）包含的dish信息
     */
    @Cacheable(value = "dishCache",key="'dish_'+#dish.getCategoryId()+'_'+#dish.getStatus()")
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList;
        //查询对应分类的菜品
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
         dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //口味信息，移动端展示？？？
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }
}
